/*
 * @author: huangww
 * @Date: 2021-03-01 11:25:47
 * @LastEditTime: 2021-03-01 14:46:43
 * @FilePath: \fmgr\src\core\mgr\TimerMgr.ts
 */
namespace core {
  /**
  * 定时器管理器
  */
  export class TimerMgr {
    private static instance: TimerMgr;

    private time: number;

    private timeStack: Array<TimerHandler>;
    public constructor() {
      this.timeStack = [];
    }

    static getInstance() {
      if (!this.instance) {
        this.instance = new TimerMgr();
      }
      return this.instance;
    }

    start() {
      egret.startTick(this.onEnterFrame, this);
    }

    register(listener: Function, thisObject: any) {

      for (let i of this.timeStack) {
        if (i.listener === listener && i.thisObject === thisObject) {
          return false;
        }
      }
      let item = {} as TimerHandler;
      item.listener = listener;
      item.thisObject = thisObject;
      this.timeStack.push(item);
    }
    unregister(listener, thisObject) {
      let length = this.timeStack.length;
      for (let i = length - 1; i >= 0; i--) {
        if (this.timeStack[i].listener === listener && this.timeStack[i].thisObject === thisObject) {
          this.timeStack.splice(i, 1);
          break;
        }
      }
    }
    private onEnterFrame(timeStamp: number) {
      if (!this.time) {
        this.time = timeStamp;
      }
      let pass = timeStamp - this.time;
      this.time = timeStamp;
      DBMgr.getInstance().advanceTime(pass / 1000);
      for (let i of this.timeStack) {
        i.listener.call(i.thisObject, pass);
      }
      return true;
    }
  }

  interface TimerHandler {
    thisObject: any;
    listener: Function;
  }
}